/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.github.zagum.speechrecognitionview.sample.slice;

import com.github.zagum.speechrecognitionview.RecognitionProgressView;
import com.github.zagum.speechrecognitionview.adapters.RecognitionListenerAdapter;
import com.github.zagum.speechrecognitionview.sample.ResourceTable;
import com.hjq.permissions.OnPermission;
import com.hjq.permissions.XXPermissions;
import com.indris.material.RippleView;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.components.Text;
import ohos.agp.text.Font;
import ohos.agp.utils.Color;
import ohos.agp.window.dialog.ToastDialog;
import ohos.ai.asr.AsrClient;
import ohos.ai.asr.AsrIntent;
import ohos.app.dispatcher.TaskDispatcher;
import ohos.utils.PacMap;
import java.util.List;

public class MainAbilitySlice extends AbilitySlice {
    private AsrClient asrClient;
    private AsrIntent initIntent;
    private RecognitionProgressView recognitionProgressView;
    private final static String TAG = "MainThisClass->";

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        getWindow().setStatusBarColor(Color.getIntColor("#3b4dac"));
        int[] colors = {
                Color.getIntColor("#3164d7"),
                Color.getIntColor("#d92d29"),
                Color.getIntColor("#eeaa10"),
                Color.getIntColor("#3164d7"),
                Color.getIntColor("#2e9641")
        };
        Text title = (Text) findComponentById(ResourceTable.Id_title);
        title.setFont(Font.DEFAULT_BOLD);
        int[] heights = {24, 28, 22, 27, 20};
        initIntent = new AsrIntent();
        initIntent.setAudioSourceType(AsrIntent.AsrAudioSrcType.ASR_SRC_TYPE_PCM);
        initIntent.setFilePath(this.getAbilityPackageContext().getExternalCacheDir().getAbsolutePath());
        recognitionProgressView = (RecognitionProgressView) findComponentById(ResourceTable.Id_recognition_view);
        recognitionProgressView.setRecognitionListener(new RecognitionListenerAdapter() {
            @Override
            public void onResults(PacMap results) {
                showResults(results);
            }

            @Override
            public void onError(int i) {
                System.out.println("onError" + "======onError:"+i);

//                if(i == 5){
//                    asrClient.stopListening(); // 停止识别
//                    asrClient.cancel(); // 取消识别
//                    asrClient.destroy();
//                    asrClient = null ;
//                    startRecognition();
//                }
//                super.onError(i);
            }
        });
        asrClient = AsrClient.createAsrClient(this).orElse(null);
        recognitionProgressView.setColors(colors);
        recognitionProgressView.setBarMaxHeightsInDp(heights);
        recognitionProgressView.setCircleRadiusInDp(2);
        recognitionProgressView.setSpacingInDp(6);
        recognitionProgressView.setIdleStateAmplitudeInDp(2);
        recognitionProgressView.setRotationRadiusInDp(10);
        recognitionProgressView.play();
        RippleView click_one = (RippleView) findComponentById(ResourceTable.Id_click_one);
        click_one.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                getPermissions();
            }
        });
        RippleView click_two = (RippleView) findComponentById(ResourceTable.Id_click_two);
        click_two.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                recognitionProgressView.stop();
                recognitionProgressView.play();
            }
        });
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    protected void onStop() {
        asrClient.stopListening(); // 停止识别
        asrClient.cancel(); // 取消识别
        asrClient.destroy();
        super.onStop();
    }


    private boolean hasSpecked = false;

    private void startRecognition() {
        TaskDispatcher taskDispatcher = getAbility().getMainTaskDispatcher();
        taskDispatcher.asyncDispatch(
                new Runnable() {
                    @Override
                    public void run() {
                        System.out.println("hasPermission" + "taskDispatcher");
                        hasSpecked = true;
                        recognitionProgressView.setSpeechRecognizer(asrClient);

                    }
                });
    }

    private void getPermissions() {
        if (hasSpecked) {
            recognitionProgressView.stop();
            recognitionProgressView.play();
            return;
        }
        XXPermissions.with(this).permission("ohos.permission.MICROPHONE", "ohos.permission.READ_USER_STORAGE", "ohos.permission.WRITE_MEDIA",
                "ohos.permission.READ_MEDIA", "ohos.permission.WRITE_USER_STORAGE").request(new OnPermission() {
            @Override
            public void hasPermission(List<String> list, boolean b) {
                System.out.println("hasPermission" + "hasPermission===" + b);

                if (b) {
                    startRecognition();
                } else {
                    new ToastDialog(getContext()).setText("获取权限失败").show();
                }
            }

            @Override
            public void noPermission(List<String> list, boolean b) {
                if (b) {
                    // 如果是被永久拒绝就跳转到应用权限系统设置页面
                    String[] permissions = new String[list.size()];
                    list.toArray(permissions);
                    XXPermissions.startPermissionActivity(MainAbilitySlice.this, permissions, this);
                } else {
                    new ToastDialog(getContext()).setText("获取权限失败").show();
                }
            }
        });
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }


    private void showResults(PacMap results) {
//        ArrayList<String> matches = results
//                .getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
//        Toast.makeText(this, matches.get(0), Toast.LENGTH_LONG).show();
    }


}
